/*
 * 代号：凤凰
 * http://www.jphenix.org
 * 2014-06-13
 * V4.0
 */
package com.jphenix.webserver.instancea;

import com.jphenix.share.util.StringUtil;
import com.jphenix.standard.docs.ClassInfo;

import java.io.*;

/**
 * ThrottledOutputStream
 * 
 * 2019-09-17 整理了代码格式
 * 
 * @author 刘虻
 * 2007-3-6下午01:36:17
 */
@ClassInfo({"2019-09-17 10:40","ThrottledOutputStream"})
public class ThrottledOutputStream extends FilterOutputStream {

	private long   maxBps; //母鸡
	private long   bytes;  //母鸡
	private long   start;  //母鸡
	private byte[] oneByte = new byte[1];
	
	/**
	 * 母鸡
	 * @author 刘虻
	 * 2008-7-9上午07:39:26
	 * @param filename 母鸡
	 * @return 母鸡
	 * @throws IOException 执行发生异常
	 */
	public static WildcardDictionary parseThrottleFile(String filename) throws IOException {
		WildcardDictionary wcd = new WildcardDictionary();
		if (filename==null || filename.length()==0) {
			return wcd;
		}
		File thFile = new File(filename);
		if (thFile.isAbsolute() == false) {
			thFile = new File(System.getProperty("user.dir", "."), thFile.getName());
		}
		BufferedReader br = new BufferedReader(new FileReader(thFile));
		try{
    		while (true) {
    			String line = br.readLine();
    			if (line == null) {
    				break;
    			}
    			int i = line.indexOf('#');
    			if (i != -1) {
    				line = line.substring(0, i);
    			}
    			line = line.trim();
    			if (line.length() == 0) {
    				continue;
    			}
    			String[] words = StringUtil.splitStr(line);
    			if (words.length != 2) {
    				throw new IOException("malformed throttle line: " + line);
    			}
    			try {
    				wcd.put(words[0], new ThrottleItem(Long.parseLong(words[1])));
    			} catch (NumberFormatException e) {
    	             try {
    	            }catch(Exception e2) {}
    				throw new IOException("malformed number in throttle line: " + line);
    			}
    		}
		}catch(Exception e) {
		    e.printStackTrace();
		}finally {
		    br.close();
		}
		return wcd;
	}

	/**
	 * 构造函数
	 * 2008-7-9上午07:40:18
	 */
	public ThrottledOutputStream(OutputStream out, long maxBps) {
		super(out);
		this.maxBps = maxBps;
		bytes = 0;
		start = System.currentTimeMillis();
	}


	/**
	 * 覆盖方法
	 * @author 刘虻
	 * 2008-7-9上午07:40:38
	 */
	@Override
    public void write(int b) throws IOException {
		oneByte[0] = (byte) b;
		write(oneByte, 0, 1);
	}


	/**
	 * 覆盖方法
	 * @author 刘虻
	 * 2008-7-9上午07:40:43
	 */
	@Override
    public void write(byte[] b, int off, int len) throws IOException {
		// Check the throttle.
		bytes += len;
		long elapsed = Math.max(System.currentTimeMillis() - start, 1);

		long bps = bytes * 1000L / elapsed;
		if (bps > maxBps) {
			// Oops, sending too fast.
			long wakeElapsed = bytes * 1000L / maxBps;
			try {
				Thread.sleep(wakeElapsed - elapsed);
			} catch (InterruptedException ignore) {
			}
		}
		// Write the bytes.
		out.write(b, off, len);
	}

}
